package com.xltt.newbleclient;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.vise.ble.DeviceScanActivity;
import com.xltt.byteutil.NotificationMessage;
import com.xltt.newbleclient.ble.BluethActivity;
//import com.xltt.newbleclient.focuslayoutmanager.ListActivity;
//import com.xltt.newbleclient.watchLayoutManager.WatchLauncherActivity;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsScan;
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions;
import com.xltt.newbleclient.bt.BluetoothActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private final String TAG = "MainActivity";
    private TextView mNotifyTxt;
    private TextView mScanResultTxt;
    private Button mScanButton;
    private Switch wechatSwitch;
    private Switch callSwitch;
    private Switch messageSwitch;
    public static final int DEFAULT_VIEW = 0x22;
    private static final int REQUEST_CODE_SCAN = 0X01;
    private String username = "601832001601";
    private String password = "qwer1234";
    private String macaddress = "";
    private final String USERNAME = "username";
    private final String PASSWORD = "password";
    private final String MACADDRESS = "macaddress";
    private final String WECHAT = "wechat";
    private final String CALL = "call";
    private final String MESSAGE = "message";

    private boolean isWechatNotifyEnabled = false;
    private boolean isCallNotifyEnabled = false;
    private boolean isMessageNotifyEnabled = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initNotify();
        mNotifyTxt = findViewById(R.id.notification_content);
        mScanResultTxt = findViewById(R.id.scanresult);
        mScanButton = findViewById(R.id.scancode);
        wechatSwitch = findViewById(R.id.notification_wechat_switch);
        callSwitch = findViewById(R.id.notification_call_switch);
        messageSwitch = findViewById(R.id.notification_message_switch);
        setCheckedListener();
        //EventBus.getDefault().register(this);//注册接收从Service发过来的msg
    }

    private void setCheckedListener() {
        wechatSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isWechatNotifyEnabled = isChecked? true : false;
                wechatSwitch.setText(isChecked? "关闭微信通知": "打开微信通知");
                Log.d(TAG, "Bevis add for isWechatNotifyEnabled: " + isWechatNotifyEnabled);
            }
        });

        callSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isCallNotifyEnabled = isChecked? true : false;
                callSwitch.setText(isChecked? "关闭电话通知": "打开电话通知");
                Log.d(TAG, "Bevis add for isCallNotifyEnabled: " + isCallNotifyEnabled);
            }
        });

        messageSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isMessageNotifyEnabled = isChecked? true : false;
                messageSwitch.setText(isChecked? "关闭短信通知": "打开短信通知");
                Log.d(TAG, "Bevis add for isMessageNotifyEnabled: " + isMessageNotifyEnabled);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void notification(NotificationMessage mNotificationMessage){
        String pkg = mNotificationMessage.getPackageName();
        String content = mNotificationMessage.getContent();
        String title = mNotificationMessage.getTitle();
        StringBuffer sbf = new StringBuffer();
        sbf.append("[包名 = " + pkg);
        sbf.append("标题 = " + title);
        sbf.append("内容 = " + content + "]");
        mNotifyTxt.setText(sbf.toString());
    }

    public void test(View view){
        if(view.getId() == R.id.ble_demo){
            startActivity(new Intent(this, DeviceScanActivity.class));
        }else if (view.getId() == R.id.test1) {
            Intent intent = new Intent(this, BluethActivity.class);
            intent.putExtra(USERNAME, username);
            intent.putExtra(PASSWORD, password);
            intent.putExtra(MACADDRESS, macaddress);
            intent.putExtra(WECHAT, isWechatNotifyEnabled);
            intent.putExtra(CALL, isCallNotifyEnabled);
            intent.putExtra(MESSAGE, isMessageNotifyEnabled);
            startActivity(intent);
        } else if (view.getId() == R.id.test2) {
            //startActivity(new Intent(this, ListActivity.class));
        } else if (view.getId() == R.id.test3) {
            //startActivity(new Intent(this, WatchLauncherActivity.class));
        } else if (view.getId() == R.id.scancode) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                this.requestPermissions(
                        new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE},
                        DEFAULT_VIEW);
            }
        }else if(view.getId() == R.id.bt){
            Intent btIntent = new Intent(this, BluetoothActivity.class);
            startActivity(btIntent);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (permissions == null || grantResults == null || grantResults.length < 2 || grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        if (requestCode == DEFAULT_VIEW) {
            //start ScankitActivity for scanning barcode
            ScanUtil.startScan(MainActivity.this, REQUEST_CODE_SCAN, new HmsScanAnalyzerOptions.Creator().setHmsScanTypes(HmsScan.ALL_SCAN_TYPE).create());
        }

    }

    private void parseOriginalValue(String value) {
        if(!"".equals(value)) {
            String[] text = value.split("&a=");
            Log.d(TAG, "Bevis add for text.length: " + text.length);
            if (text.length < 1) {
                Toast.makeText(this, "非手表二维码", Toast.LENGTH_SHORT).show();
                return;
            }
            String[] text2 = text[1].split("&b=");
            Log.d(TAG, "Bevis add for text2.length: " + text2.length);
            username = text2[0];
            String[] text3 = text2[1].split("&c=");
            Log.d(TAG, "Bevis add for text3.length: " + text3.length);
            password = text3[0];
            macaddress = text3[1];
            Log.d(TAG, "Bevis add for username: " + username + ", password: " + password + ", macaddress:" + macaddress);
            //Toast.makeText(this, "Bevis add for username: " + username + ", password: " + password + ", macaddress:" + macaddress,
            //        Toast.LENGTH_SHORT).show();
            mScanResultTxt.setText("Bevis add for username: " + username + ", password: " + password + ", macaddress:" + macaddress);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //receive result after your activity finished scanning
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        // Obtain the return value of HmsScan from the value returned by the onActivityResult method by using ScanUtil.RESULT as the key value.
        if (requestCode == REQUEST_CODE_SCAN) {
            Object obj = data.getParcelableExtra(ScanUtil.RESULT);
            if (obj instanceof HmsScan) {
                if (!TextUtils.isEmpty(((HmsScan) obj).getOriginalValue())) {
                    //Toast.makeText(this, ((HmsScan) obj).getOriginalValue(), Toast.LENGTH_SHORT).show();
                    parseOriginalValue(((HmsScan) obj).getOriginalValue());
                }
                return;
            }
        }
    }

    private void initNotify(){
        // 通知栏监控器开关
        Button notificationMonitorOnBtn = (Button)findViewById(R.id.notification_monitor_on_btn);
        notificationMonitorOnBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isEnabled()) {
                    startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
                } else {
                    Toast.makeText(getApplicationContext(), "监控器开关已打开", Toast.LENGTH_SHORT).show();
                    wechatSwitch.setChecked(true);
                    callSwitch.setChecked(true);
                    messageSwitch.setChecked(true);
                }
            }
        });

        Button notificationMonitorOffBtn = (Button)findViewById(R.id.notification_monitor_off_btn);
        notificationMonitorOffBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //
                if (isEnabled()) {
                    startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
                } else {
                    Toast.makeText(getApplicationContext(), "监控器开关已关闭", Toast.LENGTH_SHORT).show();
                    wechatSwitch.setChecked(false);
                    callSwitch.setChecked(false);
                    messageSwitch.setChecked(false);
                }
            }
        });
    }

    // 判断是否打开了通知监听权限
    private boolean isEnabled() {
        String pkgName = getPackageName();
        final String flat = Settings.Secure.getString(getContentResolver(), "enabled_notification_listeners");
        if (!TextUtils.isEmpty(flat)) {
            final String[] names = flat.split(":");
            for (int i = 0; i < names.length; i++) {
                final ComponentName cn = ComponentName.unflattenFromString(names[i]);
                if (cn != null) {
                    if (TextUtils.equals(pkgName, cn.getPackageName())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        if(EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }
}
